package cn.lichenfei.app.satoken;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class Demo implements ApplicationRunner {

    @Autowired
    WebApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 拿到Handler适配器中的全部方法
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
        List<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : methodMap.keySet()) {
            Set<String> urlSet = info.getPatternsCondition().getPatterns();//一个方法对应多个url
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            log.info("url:{}", urlSet);
            RequestMethod requestMethod = methods.stream().findFirst().orElse(null);//获取RequestMethod
            urlList.addAll(urlSet
                    .stream()
                    .map(url -> requestMethod == null ? url : requestMethod.name() + ":" + url)
                    .collect(Collectors.toList()));
        }
        log.info("urlList : {}", urlList);
    }
}
